package cn.xiaye.httpserver;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Http请求信息
 * 
 * @author 王夏夜
 * 
 */
public class Request {
	private String mehod;
	private String action;
	private String version;
	/**
	 * http 请求头信息
	 */
	HashMap<String, String> header = new HashMap<String, String>();
	/**
	 * http请求参数信息
	 */
	HashMap<String, String> parameters = new HashMap<String, String>();
	/**
	 * 拆分头信息的正则表达式
	 */
	public static Pattern ptnHeader = Pattern.compile("^([a-zA-Z_0-9-]+):(.*)$");
	public static Pattern ptnParam = Pattern.compile("(.*)={1}(.*)");

	public Request(String str) {
		matcherHeader(str);
		matcherParameters(str);
	}

	/**
	 * 目前只实现get方式提交的参数
	 * 
	 * @param str
	 */
	private void matcherParameters(String str) {
		String substr = str.substring(0, str.indexOf("\n"));
		String[] strarr = substr.split(" ");
		this.mehod = strarr[0];
		version = strarr[2].trim();
		if (!strarr[1].contains("?")) {
			this.action = strarr[1];
		} else {
			this.action = strarr[1].substring(0, strarr[1].indexOf("?"));
			String pramstr = strarr[1].substring(strarr[1].indexOf("?") + 1);
			String[] pramarr = pramstr.split("&");
			for (int i = 0; i != pramarr.length; i++) {
				Matcher ma = ptnParam.matcher(pramarr[i]);
				if (ma.find()) {
					String key = ma.group(1);
					String value = ma.group(2);
					parameters.put(key, value);
				}
			}
		}
	}

	private void matcherHeader(String str) {
		String[] head = str.split("\n");
		for (String h : head) {
			Matcher m = ptnHeader.matcher(h);
			if (m.find()) {
				String key = m.group(1).trim();
				String value = m.group(2).trim();
				header.put(key, value);
			}
		}
	}

	public HashMap<String, String> getHeader() {
		return header;
	}

	public void setHeader(HashMap<String, String> header) {
		this.header = header;
	}

	public HashMap<String, String> getParameters() {
		return parameters;
	}

	public void setParameters(HashMap<String, String> parameters) {
		this.parameters = parameters;
	}

	public String getHeader(String key) {
		return this.header.get(key);
	}

	public String getMehod() {
		return mehod;
	}

	public void setMehod(String mehod) {
		this.mehod = mehod;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getParameter(String key) {
		return this.parameters.get(key);
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

}
